package mc

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/spf13/cast"
	"net/url"
	"os"
	"path/filepath"
	"reflect"
	"strings"
	"unicode"
)

// 条件判断
func Iif(condition bool, trueValue interface{}, falseValue interface{}) interface{} {
	if condition {
		return trueValue
	} else {
		return falseValue
	}
}

// 驼峰转下划线小写 userName(UserName) -> user_name
func CamelToCase(str string) string {
	s := []rune(str)
	dest := ""
	for i, v := range s {
		if unicode.IsUpper(v) {
			if i > 0 {
				dest += "_"
			}
		}
		dest += fmt.Sprintf("%c", v)
	}
	return strings.ToLower(dest)
}

//  转大驼峰写法 user_name -> UserName
func CaseToUpperCamel(str string) string {
	str = strings.Replace(str, "_", " ", -1)
	str = strings.Title(str)
	return strings.Replace(str, " ", "", -1)
}

// 转转小驼峰 user_name -> userName
func CaseToLowerCamel(str string) string {
	return LowerFirst(CaseToUpperCamel(str))
}

//  转首字母大写
func UpperFirst(str string) string {
	for i, v := range str {
		return string(unicode.ToUpper(v)) + str[i+1:]
	}
	return ""
}

//  转首字母小写
func LowerFirst(str string) string {
	for i, v := range str {
		return string(unicode.ToLower(v)) + str[i+1:]
	}
	return ""
}

// 查找元素是否在数组中
// @param obj 待查找的对象
// @param target 查找范围对象
// @return 是否存在
func InArray(obj interface{}, target interface{}) bool {
	targetValue := reflect.ValueOf(target)
	switch reflect.TypeOf(target).Kind() {
	case reflect.Slice, reflect.Array:
		for i := 0; i < targetValue.Len(); i++ {
			if targetValue.Index(i).Interface() == obj {
				return true
			}
		}
	case reflect.Map:
		if targetValue.MapIndex(reflect.ValueOf(obj)).IsValid() {
			return true
		}
	}
	return false
}

// 根据页码和大小转换成数据库查询语句使用的offset、limit
func GetOffsetLimit(page int, pageSize int) (offset int, limit int) {
	if page <= 0 {
		page = 1
	}
	if pageSize <= 0 {
		pageSize = option.Request.PageSizeValue
	}
	limit = pageSize
	offset = (page - 1) * pageSize
	return
}

// UrlValue 转换成 RequestValue
func UrlValueToRequestValue(values url.Values) (requestValues map[string]interface{}) {
	requestValues = make(map[string]interface{})
	for key, value := range values {
		key := strings.ReplaceAll(key, "[]", "")
		//if len(value) <= 1 {
			if v, err := url.QueryUnescape(value[0]); err != nil{
				requestValues[key] = value[0]
			}else{
				requestValues[key] = v
			}
		//} else {
		//	for i, _ := range value {
		//		if v, err := url.QueryUnescape(value[i]); err == nil{
		//			value[i] = v
		//		}
		//		//value[i], _ = url.QueryUnescape(value[i])
		//	}
		//	requestValues[key] = value
		//}
	}
	return
}

// 生成一串n个相同字符串组成的的字符串
// @param str 原字符串
// @n 重复次数
// @return s 生成的字符串
func RepeatString(str string, n int) (s string) {
	s = ""
	for i := 0; i < n; i++ {
		s += str
	}
	return
}

func Split(s interface{}, sep string) []string {
	if s == nil {
		return nil
	}
	t := reflect.TypeOf(s).Kind()
	if t == reflect.Array || t == reflect.Slice {
		return cast.ToStringSlice(s)
	} else {
		return strings.Split(cast.ToString(s), sep)
	}
}

func Join(s interface{}, sep string) string {
	if s == nil {
		return ""
	}
	t := reflect.TypeOf(s).Kind()
	if t == reflect.Array || t == reflect.Slice {
		return strings.Join(cast.ToStringSlice(s), sep)
	} else {
		return cast.ToString(s)
	}
}

func IsEmpty(v interface{}) bool {
	if v == nil {
		return true
	}
	t := reflect.ValueOf(v)
	if reflect.DeepEqual(t.Interface(), reflect.Zero(t.Type()).Interface()) {
		return true
	}
	//v1 := fmt.Sprintf("%v", v)
	//if v1 == "" || v1 == "[]" || v1 == "map[]"{
	//	return true
	//}
	return false
}

// 判断文件是否存在  存在返回 true 不存在返回false
func CheckFileIsExist(fileName string) bool {
	var exist = true
	if _, err := os.Stat(fileName); os.IsNotExist(err) {
		exist = false
	}
	return exist
}

// 创建文件
func CreateFile(fileName string) (err error) {
	if !CheckFileIsExist(fileName) {
		filePath, _ := filepath.Abs(filepath.Dir(fileName))
		_ = os.MkdirAll(filePath, os.ModePerm)
		_, err = os.Create(fileName)
	}
	return
}

// 数组去重
func RemoveRepeatedElement(arr []string) (newArr []string) {
	newArr = make([]string, 0)
	for i := 0; i < len(arr); i++ {
		repeat := false
		for j := i + 1; j < len(arr); j++ {
			if arr[i] == arr[j] {
				repeat = true
				break
			}
		}
		if !repeat {
			newArr = append(newArr, arr[i])
		}
	}
	return
}


// interface 转json对象
// data 数据对象
// escapeHtml 是否对特殊字符进行转义
func JsonEncoder(data interface{}, escapeHtml bool) (string, error) {
	bf := bytes.NewBuffer([]byte{})
	jsonEncoder := json.NewEncoder(bf)
	jsonEncoder.SetEscapeHTML(escapeHtml)
	if e := jsonEncoder.Encode(data); e != nil{
		return "", e
	}else{
		return bf.String(), nil
	}
}
